package online.inote.naruto.api.access.admin.modules.system.controller;

import online.inote.naruto.api.access.admin.modules.base.controller.BaseController;
import online.inote.naruto.api.access.admin.modules.system.entity.AuthInterfaceEntity;
import online.inote.naruto.api.access.admin.modules.system.service.AuthInterfaceService;
import online.inote.naruto.common.utils.response.ExtendResponse;
import online.inote.naruto.common.utils.response.Response;
import online.inote.naruto.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @description 系统授权接口Controller
 * @author XQF.Sui
 * @date 2021/08/06 19:52
 */
@RestController
@RequestMapping(value = "authInterface")
public class AuthInterfaceController extends BaseController {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  private final AuthInterfaceService authInterfaceService;

  public AuthInterfaceController(AuthInterfaceService authInterfaceService) {
    this.authInterfaceService = authInterfaceService;
  }

  @PostMapping(value = "enable")
  public Response<Object> enable(
      @RequestBody @Valid AuthInterfaceEntity aie, BindingResult result) {

    if (result.hasErrors()) {
      return ExtendResponse.fail(
          StringUtils.join(
              result.getAllErrors().stream()
                  .map(ObjectError::getDefaultMessage)
                  .collect(Collectors.toList())));
    }

    try {
      if (aie.getEnable()) {
        authInterfaceService.save(aie);
      } else {
        authInterfaceService.delete(aie);
      }
    } catch (Exception e) {
      logger.error("授权失败", e);
      return ExtendResponse.fail("授权失败");
    }

    return ExtendResponse.success();
  }
}
